package com.donfelix.looknews.common;

import android.app.Application;
import android.content.Context;
import android.support.v7.app.AppCompatDelegate;

import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;

/**
 * Created by Don on 2017/3/24.
 * Desc
 */

public class LookNewsApplication extends Application {

    public static final String TAG = "LookNewsApplication";
    public static final boolean DEBUG = true;
    private static LookNewsApplication application;
    private static Context context;
    private static int mainTid;
    /**
     * Activity集合，来管理所有的Activity
     */
    private static List<BaseActivity> activities;

    /**
     * app主题
     */
    static {
        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        application = this;
        context = this;
        mainTid = android.os.Process.myPid();
        activities = new LinkedList<>();
    }

    /**
     * 获取全局application
     *
     * @return
     */
    public static LookNewsApplication getApplication() {
        return application;
    }

    /**
     * 获取全局context
     *
     * @return
     */
    public static Context getContext() {
        return context;
    }

    /**
     * 获取主线程ID
     *
     * @return
     */
    public static int getMainTid() {
        return mainTid;
    }

    /**
     * 添加一个Activity
     *
     * @param activity
     */
    public void addActivity(BaseActivity activity) {
        activities.add(activity);
    }

    /**
     * 结束一个Activity
     *
     * @param activity
     */
    public void removeActivity(BaseActivity activity) {
        activities.remove(activity);
    }

    /**
     * 结束当前所有Activity
     */
    public static void clearActivities() {
        ListIterator<BaseActivity> iterator = activities.listIterator();
        BaseActivity activity;
        while (iterator.hasNext()) {
            activity = iterator.next();
            if (activity != null) {
                activity.finish();
            }
        }
    }

    /**
     * 退出应运程序
     */
    public static void quiteApplication() {
        clearActivities();
        System.exit(0);
    }
}
